const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Permission = require('../models/Permission');

// 获取所有权限
router.get('/', auth, async (req, res) => {
  try {
    const permissions = await Permission.find();
    res.json(permissions);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建权限
router.post('/', auth, async (req, res) => {
  try {
    const { name, description, code } = req.body;
    const permission = new Permission({
      name,
      description,
      code
    });
    await permission.save();
    res.status(201).json(permission);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新权限
router.put('/:id', auth, async (req, res) => {
  try {
    const { name, description, code } = req.body;
    const permission = await Permission.findByIdAndUpdate(
      req.params.id,
      { name, description, code },
      { new: true }
    );
    
    if (!permission) {
      return res.status(404).json({ message: '权限不存在' });
    }
    
    res.json(permission);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除权限
router.delete('/:id', auth, async (req, res) => {
  try {
    const permission = await Permission.findByIdAndDelete(req.params.id);
    if (!permission) {
      return res.status(404).json({ message: '权限不存在' });
    }
    res.json({ message: '权限已删除' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 